import { Injectable } from "@nestjs/common";
import { CreateLogDto } from "./dto/create-log.dto";
import { UpdateLogDto } from "./dto/update-log.dto";
import { InjectRepository } from "@nestjs/typeorm";
import { Like, Repository } from "typeorm";
import { Log } from "@/modules/log/entities/log.entity";
import { ResultData } from "@/common/utils/result";
import { instanceToPlain } from "class-transformer";

@Injectable()
export class LogService {
    constructor(
        @InjectRepository(Log)
        private readonly logRepository: Repository<Log>
    ) {
    }
    
    async create(createLogDto: CreateLogDto) {
        return ResultData.ok(await this.logRepository.save(createLogDto));
    }
    
    async findAll(findAllDto) {
        const { page, size, userFlags, type, status, ip } = findAllDto;
        const take = size || 15;
        const skip = ((page || 1) - 1) * take;
        const where = {
            ...(type === 0 || type ? { type } : null),
            ...(status === 0 || status ? { status } : null),
            ...(userFlags ? { userFlags: Like(`%${userFlags}%`) } : null),
            ...(ip ? { ip: Like(`%${ip}%`) } : null)
        };
        return ResultData.rowOk(instanceToPlain(await this.logRepository.findAndCount({
            order: {
                id: "DESC"
            },
            where,
            skip,
            take
        })));
    }
    
    findOne(id: number) {
        return `This action returns a #${id} log`;
    }
    
    update(id: number, updateLogDto: UpdateLogDto) {
        return `This action updates a #${id} log`;
    }
    
    remove(id: number) {
        return `This action removes a #${id} log`;
    }
}
